<template>
    <el-dialog title="元数据参数修改" :visible.sync="show" :show-close="false">
        <el-row type="flex">
            <el-col :span="4" align="right">编码：</el-col>
            <el-col :span="8" v-text="metaData.code"></el-col>
            <el-col :span="4" align="right">名称：</el-col>
            <el-col :span="8" v-if="metaData.def" v-text="metaData.def.name"></el-col>
        </el-row>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px">
            <el-form-item label="值：" prop="metaVal">
                <el-input type="textarea" v-model="ruleForm.metaVal" autosize></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="saveMeta('ruleForm')">确 定</el-button>
        </div>
    </el-dialog>
</template>
<script>
    import axios from '~plugins/axios';

    export default {
        props: {
            visible: Boolean,
            metaData: Object
        },
        data() {
            return {
                ruleForm: {
                    metaVal: ''
                },
                rules: {
                    metaVal: [
                        {required: true, message: '请填写值内容', trigger: 'change'}
                    ]
                }
            };
        },
        computed: {
            show() {
                return this.visible;
            }
        },
        methods: {
            close() {
                this.show = false;
                this.$emit('on-cancel', false);
            },
            // 保存数据-
            saveMeta(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        try {
                            var metaVal = JSON.stringify(JSON.parse(this[name]['metaVal']));
                            axios.post('/api/metaParam/update', {
                                id: this.metaData.id,
                                val: metaVal
                            }).then(() => {
                                this.show = false;
                                this.$emit('on-success', false);
                                this.$message({showClose: true, message: '修改成功', type: 'success'});
                            }).catch(() => {
                                this.$message({showClose: true, message: '修改失败', type: 'error'});
                            });
                        } catch (e) {
                            this.$message({showClose: true, message: '内容格式错误', type: 'error'});
                        }
                    }
                });
            }
        },
        watch: {
            metaData(data) {
                this.ruleForm.metaVal = JSON.stringify((typeof data.val === 'undefined' ? {} : data.val), null, 4); // 设置默认值
            }
        }
    };
</script>